import json
import os

import pymongo
from xpinyin import Pinyin


class WebMongo():

    def __init__(self, mongoserver='mongodb://localhost:27017/', mongodb='webdb'):
        self.casepath='../webui/webuidata/webtestcase'

        self.mongoserver = mongoserver
        self.myclient = pymongo.MongoClient(mongoserver)
        self.mymongodb = self.myclient[mongodb]
    # 用于mongodb数据库存储

    '''
    按json文档名称分表插入所有汇总的用例，如果文档名称为汉字 则转换为拼音
    '''

    def json_to_mongo(self):

        case_list = os.listdir(self.casepath)

        if case_list:

            for case_name in case_list:

                with open(self.casepath + '/' + case_name) as file:
                    json_obj = json.load(file)

                    try:
                        p = Pinyin()
                        mongo_col = p.get_pinyin(os.path.splitext(case_name)[0], '')
                    except:
                        mongo_col = os.path.splitext(case_name)[0]


                    self.mymongodb[mongo_col].insert_one(json_obj)
    def mongo_to_dict(self):
        case_dict = dict()
        col_list = self.mymongodb.list_collection_names()

        for my_col in col_list:
            case_ = self.mymongodb[my_col].find({}).sort('_id', -1).limit(1)
            for case in case_:
                for key, value in case.items():
                    if not key == '_id':
                        case_dict[key] = value

        return case_dict

    def save_json(self):
        case_list = self.mongo_to_dict()
        with open('../webui/webuidata/caselist.json', mode='w') as file:
            json.dump(case_list, file, indent=4, ensure_ascii=False)
